<?php
/**
 +------------------------------------------------------------------------------
 * 文件工具类
 +------------------------------------------------------------------------------
 */
class FileTool
{	
	/**
     +----------------------------------------------------------
     * 文件目录检测
     +----------------------------------------------------------
     * @param string $path  文件路径
     +----------------------------------------------------------
     * @return void
     +----------------------------------------------------------
     */
	public static function dir($path)
	{
		if (!is_dir($path)){
			if (is_writable(dirname($path))){
				try{
					mkdir($path, 0777, true);
				}catch ( Exception $e ){
					return false;
				}
			}else{
				return false;
			}
		}
		
		return true;
	}

	/**
     +----------------------------------------------------------
     * 写文件
     +----------------------------------------------------------
     * @param string $file  文件路径
     * @param string $data  写文件内容
     +----------------------------------------------------------
     * @return void
     +----------------------------------------------------------
     */
	public static function write($file, $data)
	{
		// 检查目录是否存在
		if (!FileTool::dir(dirname($file))) return false;
		
		$fp = fopen($file, 'wb');
		
		// 独占锁
		if (!flock($fp, LOCK_EX | LOCK_NB)) return false;
		
		fwrite($fp, $data);
		
		// 解锁
		flock($fp, LOCK_UN);
		
		// 关闭
		fclose($fp);
		
		// 设置权限
		@chmod($file, 0777);
	} 

	/**
     +----------------------------------------------------------
     * 读操作
     +----------------------------------------------------------
     * @param string $file  文件路径
     +----------------------------------------------------------
     * @return string 文件内容
     +----------------------------------------------------------
     */
	public static function read($file)
	{
		if (!is_file($file))return false;
		
		// 打开
		$fp = fopen($file, "rb");

		// 共享锁
		if (!flock($fp, LOCK_SH | LOCK_NB))return false;
		
		$str = fread($fp, filesize($file));
		
		// 解锁
		flock($fp, LOCK_UN);
		
		// 关闭
		fclose($fp);
		
		return $str;
	}
}
?>